package com.s10.ecloud.web.action;

import java.util.List;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.ActionSupport;
import com.s10.ecloud.web.Constants;
import com.s10.ecloud.web.model.EnterpriseUser;
import com.s10.ecloud.web.model.Role;
import com.s10.ecloud.web.model.User;
import com.s10.ecloud.web.service.IUserService;
import com.s10.ecloud.web.util.EmailUtils;
import com.s10.ecloud.web.util.GenerateLinkUtils;
import com.s10.ecloud.web.util.MD5;

/**
 * 
 * 企业用户，注册相关处理
 * 
 * @author Kevin
 * 
 */
public class A020100Action extends ActionSupport {

	@Resource
	private IUserService userService = null;

	/** 处理登录请求 */
	@Action(value = "/toEntUserRegist", results = { @Result(name = "success", location = "/page/ent/registEntUser.jsp") })
	public String toEntUserRegist() throws Exception {

		return this.SUCCESS;
	}

	/** 处理会员注册请求 */
	@Action(value = "/registEntUser", results = {
			@Result(name = "success", location = "/page/ent/registSuccess.jsp"),
			@Result(name = "error", location = "/page/ent/registEntUser.jsp") })
	public String registEntUser() throws Exception {

		// 1 注册信息验证
		if (!this.validateAddMember()) {
			return ERROR;
		}
		// 3 设置以下几个字段的初始值

		EnterpriseUser enterpriseUser = new EnterpriseUser();
		enterpriseUser.setAddress(this.getAddress());
		enterpriseUser.setCommerceNo(this.getCommerceNo());
		enterpriseUser.setCompanyName(this.getCompanyName());
		enterpriseUser.setDistrict(null);
		enterpriseUser.setEmail(this.getEmail());

		enterpriseUser.setMobile(this.getMobile());
		enterpriseUser.setName(this.getName());
		enterpriseUser.setOnline(false);

		enterpriseUser.setPhone(this.getPhone());
		enterpriseUser.setQq(this.getQq());
		enterpriseUser.setGender("1");

		// 企业用户
		enterpriseUser.setRole(this.userService
				.getRoleById(Constants.USER_TYPE_ENT));
		enterpriseUser.setState(Constants.USER_ACTIVE_STATE_WAITING_ACTIVE);

		enterpriseUser.setWebsite(this.getWebsite());
		enterpriseUser.setZipcode(this.getZipcode());

		java.sql.Date dateNow = new java.sql.Date(
				new java.util.Date().getTime());
		enterpriseUser.setRegistDate(dateNow);
		enterpriseUser.setUpdateDate(dateNow);
		enterpriseUser.setLoginDate(dateNow);

		GenerateLinkUtils.generateCheckcode(enterpriseUser);

		// 对登录密码进行MD5加密
		enterpriseUser.setPassword(MD5.MD5Encode(this.getPassword()));
		// 4 保存新增的注册会员
		userService.addUser(enterpriseUser);

		// 注册成功后,发送帐户激活链接
		EmailUtils.sendAccountActivateEmail(enterpriseUser);

		this.addActionMessage("注册成功，请去邮箱激活！");
		return this.SUCCESS;
	}

	/** 手动进行新增注册会员的表单验证 */
	private boolean validateAddMember() {

		/** 账户信息验证 */
		// Email合法性验证
		if (this.getEmail() == null || this.getEmail().trim().length() < 1) {
			addFieldError("email", getText("请输入邮箱"));
		} else {// 登录邮箱是否已被占用
			if (!Pattern.matches("\\w+(\\.\\w+)*@\\w+(\\.\\w+)+", this
					.getEmail().trim())) {
				addFieldError("email", getText("请输入有效的邮箱地址"));
			} else {
				int count = userService.getUserCountByEmail(this.getEmail());
				if (count > 0) {
					addFieldError("email", getText("该邮箱已被使用，请更换其它邮箱"));
				}
			}
		}
		// 登录密码必填
		if (this.getPassword() == null
				|| this.getPassword().trim().length() < 1) {
			addFieldError("loginpwd", getText("请输入密码"));
		} else {
			if (this.getPassword().trim().length() < 6
					|| this.getPassword().trim().length() > 20) {
				addFieldError("loginpwd", getText("密码长度只能在6-20位字符之间"));
			} else {
				// 核对两次输入的密码是否一致
				String againPwd = this.getConfirmPassword();
				if (againPwd == null || againPwd.trim().length() < 1
						|| !againPwd.trim().equals(this.getPassword())) {
					addFieldError("loginpwd", getText("两次输入密码不一致"));
				}
			}
		}

		/** 联系人信息验证 */
		// 联系人姓名
		if (this.getName() == null || this.getName().trim().length() < 1) {
			addFieldError("name", getText("请输入联系人姓名"));
		}
		// 固定电话
		if (this.getPhone() != null
				&& this.getPhone().trim().length() > 0
				&& !Pattern.matches("^[0-9\\-()（）]{7,18}$", this.getPhone()
						.trim())) {
			addFieldError("phone", getText("member_validation_phone"));
		}
		// 手机
		if (this.getMobile() != null
				&& this.getMobile().trim().length() > 0
				&& !Pattern.matches("^0?(13|15|18|14)[0-9]{9}$", this
						.getMobile().trim())) {
			addFieldError("mobile", getText("member_validation_phone"));
		}

		// QQ
		if (this.getQq() == null || this.getQq().trim().length() < 1) {
			addFieldError("QQ", getText("请输入QQ号码"));
		}

		/** 公司信息 */
		// 公司名称
		if (this.getCompanyName() == null
				|| this.getCompanyName().trim().length() < 1) {
			addFieldError("companyName", getText("请输入公司名称"));
		}
		// TODO 公司所在地

		// 公司地址
		if (this.getAddress() == null || this.getAddress().trim().length() < 1) {
			addFieldError("address", getText("请输入公司地址"));
		}

		// 公司邮编
		if (this.getZipcode() == null || this.getZipcode().trim().length() < 1) {
			addFieldError("address", getText("请输入公司邮编"));
		}
		// 使用正则表达式验证公司邮编
		else if (!Pattern.matches("\\d{6}", this.getZipcode().trim())) {
			addFieldError("zip", getText("公司邮编不正确"));
		}

		// 公司网址
		if (this.getWebsite() == null || this.getWebsite().trim().length() < 1) {
			addFieldError("website", getText("请输入公司网址"));
		}
		// 使用正则表达式验证公司网址
		else if (!Pattern.matches(
				"^http[s]?:\\/\\/([\\w-]+\\.)+[\\w-]+([\\w-./?%&#=]*)?$", this
						.getWebsite().trim())) {
			addFieldError("website", getText("公司网址输入不正确"));
		}

		// 工商登记号
		if (this.getCommerceNo() == null
				|| this.getCommerceNo().trim().length() < 1) {
			addFieldError("commerceNo", getText("请输入工商登记号"));
		} else {
			List<User> userLIst = userService.getEntUserByCommerceNo(this
					.getCommerceNo());

			if (userLIst.size() > 0) {
				addFieldError("commerceNo", getText("工商登记号已经存在，请重新输入"));
			}
		}

		// 表单验证失败
		if (hasFieldErrors()) {
			return false;
		} else {
			return true;
		}
	}

	private String email;
	private String password;
	private String confirmPassword;

	private String name;
	private String phone;
	private String mobile;
	private String qq;

	private String companyName;
	private String address;
	private String zipcode;
	private String website;
	private String commerceNo;

	/**
	 * @return the email
	 */
	public String getEmail() {
		return email;
	}

	/**
	 * @param email
	 *            the email to set
	 */
	public void setEmail(String email) {
		this.email = email;
	}

	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * @param password
	 *            the password to set
	 */
	public void setPassword(String password) {
		this.password = password;
	}

	/**
	 * @return the confirmPassword
	 */
	public String getConfirmPassword() {
		return confirmPassword;
	}

	/**
	 * @param confirmPassword
	 *            the confirmPassword to set
	 */
	public void setConfirmPassword(String confirmPassword) {
		this.confirmPassword = confirmPassword;
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name
	 *            the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the phone
	 */
	public String getPhone() {
		return phone;
	}

	/**
	 * @param phone
	 *            the phone to set
	 */
	public void setPhone(String phone) {
		this.phone = phone;
	}

	/**
	 * @return the mobile
	 */
	public String getMobile() {
		return mobile;
	}

	/**
	 * @param mobile
	 *            the mobile to set
	 */
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}

	/**
	 * @return the qq
	 */
	public String getQq() {
		return qq;
	}

	/**
	 * @param qq
	 *            the qq to set
	 */
	public void setQq(String qq) {
		this.qq = qq;
	}

	/**
	 * @return the companyName
	 */
	public String getCompanyName() {
		return companyName;
	}

	/**
	 * @param companyName
	 *            the companyName to set
	 */
	public void setCompanyName(String companyName) {
		this.companyName = companyName;
	}

	/**
	 * @return the address
	 */
	public String getAddress() {
		return address;
	}

	/**
	 * @param address
	 *            the address to set
	 */
	public void setAddress(String address) {
		this.address = address;
	}

	/**
	 * @return the zipcode
	 */
	public String getZipcode() {
		return zipcode;
	}

	/**
	 * @param zipcode
	 *            the zipcode to set
	 */
	public void setZipcode(String zipcode) {
		this.zipcode = zipcode;
	}

	/**
	 * @return the website
	 */
	public String getWebsite() {
		return website;
	}

	/**
	 * @param website
	 *            the website to set
	 */
	public void setWebsite(String website) {
		this.website = website;
	}

	/**
	 * @return the commerceNo
	 */
	public String getCommerceNo() {
		return commerceNo;
	}

	/**
	 * @param commerceNo
	 *            the commerceNo to set
	 */
	public void setCommerceNo(String commerceNo) {
		this.commerceNo = commerceNo;
	}
}
